'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useEffect,
  useRef,
  useState,
} from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { queryPasswordPublicKey, updateUserPassword } from '@/services/api';
import type { IDifference, IUser } from '@/interfaces';
import diff from 'microdiff';
import { nanoid } from 'nanoid';
import type JSEncrypt from 'jsencrypt';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Box from '@/app/[locale]/admin/common/box';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateUserPassword({
  source,
  translatedFields,
}: {
  source: IUser;
  translatedFields: PrefixedTTranslatedFields<'userAdminPage'>;
}) {
  const jsEncryptRef = useRef<JSEncrypt | null>(null);
  const [form, setForm] = useState<{
    password?: string;
  }>({
    password: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [randomPassword, setRandomPassword] = useState('');
  const { show } = useToast();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const queryPasswordPublicKeyQuery = useQuery(
    ['/key', '/public', '/password'],
    async () => {
      return (await queryPasswordPublicKey()) as string;
    },
    {
      enabled: false,
    },
  );

  const updateUserPasswordMutation = useMutation(updateUserPassword);

  useEffect(() => {
    const diffData = diff(
      {
        password: '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const data = getDiffData(differenceData);
      const password = await getEncryptedPassword(data.password);
      const id = source.id;
      await updateUserPasswordMutation.mutateAsync({
        id,
        data: {
          ...data,
          password,
        },
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateUserPasswordMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
      setRandomPassword('');
      setForm({ ...form, password: '' });
    }
  }

  function onClickGenerateRandomPassword() {
    const rPassword = nanoid();
    const password = rPassword.substring(0, Math.floor(rPassword.length / 2));
    setRandomPassword(password);
    setForm({ ...form, password });
  }

  function checkForm() {
    const { password } = form;
    if (!source.username) {
      throw translatedFields.tip.usernameRequired;
    } else if (!password) {
      throw translatedFields.tip.passwordRequired;
    }
  }

  async function getJsEncrypt(): Promise<JSEncrypt> {
    let jsEncrypt;
    if (jsEncryptRef.current) {
      jsEncrypt = jsEncryptRef.current;
    } else {
      const JSEncrypt = (await import('jsencrypt')).JSEncrypt;
      jsEncrypt = new JSEncrypt();
      jsEncryptRef.current = jsEncrypt;
    }
    return jsEncrypt;
  }

  async function getEncryptedPassword(password: string): Promise<string> {
    const jsEncrypt = await getJsEncrypt();
    const result = await queryPasswordPublicKeyQuery.refetch({
      throwOnError: true,
    });
    const publicKey = result.data;
    if (!publicKey) {
      throw translatedFields.tip.encryptDataFailed;
    }

    jsEncrypt.setPublicKey(publicKey);
    const encryptedData = jsEncrypt.encrypt(password);
    if (!encryptedData) {
      throw translatedFields.tip.encryptDataFailed;
    }

    return encryptedData;
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            <span className="user-select-none">
              {translatedFields.properties.password}
            </span>
            {randomPassword && (
              <span className="mx-2 text-secondary">({randomPassword})</span>
            )}
          </label>
          <div className="input-group">
            <input
              type="password"
              name="password"
              value={form.password}
              onChange={onChangeForm}
              className="form-control"
              autoComplete="password"
            />
            <button
              onClick={onClickGenerateRandomPassword}
              className="btn btn-outline-secondary"
              type="button"
            >
              {translatedFields.properties.randomPassword}
            </button>
          </div>
        </div>

        <button
          type="submit"
          disabled={updateUserPasswordMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateUserPasswordMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
